package com.example.venadaoa.net;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import com.android.internal.http.multipart.MultipartEntity;
import com.duowan.mobile.netroid.DefaultRetryPolicy;
import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.request.ImageRequest;
import com.duowan.mobile.netroid.request.StringRequest;
import com.example.venadaoa.LoginActivity;
import com.example.venadaoa.R;
import com.example.venadaoa.VenadaOAApplication;
import com.example.venadaoa.datamanager.ServerResult;
import com.example.venadaoa.tool.CProgressDialog;
import com.example.venadaoa.tool.LogUtil;
import com.example.venadaoa.tool.ToastHelp;
import com.example.venadaoa.tool.Utils;
import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.json.JSONObject;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;



public class NetUtils {


    public interface NetCallBack<T> {
        public void success(T rspData);

        public void failed(String msg);
    }

    //    public static final String BASE_URL = "https://114.80.100.202:85/";
//    public static final String BASE_URL = "http://ca.83soft.cn:85/";
//    public static final String IMAGE_URL = "http://114.80.100.202:8080";
    private static RequestQueue mQueue = Netroid.newRequestQueue(VenadaOAApplication.getContext());


    public static void stringGet(final Context context, String url ,final String msg, final NetCallBack<String> callBack) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络异常！");
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);

        LogUtil.d( "net url = " + url);
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Listener<String>() {

                    @Override
                    public void onSuccess(String rsp) {
                        LogUtil.d( "net response = " + rsp);

                        if (callBack != null)
                            if (rsp != null ) {
                                callBack.success(rsp);
                            }
                    }

                    @Override
                    public void onPreExecute() {
                        super.onPreExecute();
                        if (msg != null) {
                            progressDialog.setMessage(msg);
                            progressDialog.setCancelable(true);
                            try {
                                if (!progressDialog.isShowing()) {
                                    progressDialog.show();
                                }
                            } catch (Exception e) {

                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        try {
                            progressDialog.cancel();
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    public void onError(NetroidError error) {
                        if (callBack != null)
                            callBack.failed("网络异常！");
                    }
                });
        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        request.setCacheExpireTime(TimeUnit.SECONDS, 3);
        mQueue.add(request);
    }

    public static void imageGet(final Context context, Map<String,String> params,String url ,final String msg, final NetCallBack<Bitmap> callBack) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络异常！");
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);

        LogUtil.d( "net url = " + url);
        ImageParasRequest request = new ImageParasRequest( url,params,
                new Listener<Bitmap>() {

                    @Override
                    public void onSuccess(Bitmap rsp) {
                        LogUtil.d( "net response = " + rsp);

                        if (callBack != null)
                            if (rsp != null ) {
                                callBack.success(rsp);
                            }
                    }

                    @Override
                    public void onPreExecute() {
                        super.onPreExecute();
                        if (msg != null) {
                            progressDialog.setMessage(msg);
                            progressDialog.setCancelable(true);
                            try {
                                if (!progressDialog.isShowing()) {
                                    progressDialog.show();
                                }
                            } catch (Exception e) {

                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        try {
                            progressDialog.cancel();
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    public void onError(NetroidError error) {
                        if (callBack != null)
                            callBack.failed("网络异常！");
                    }
                },200,200, Bitmap.Config.ARGB_8888);
        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*4, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        request.setCacheExpireTime(TimeUnit.SECONDS, 3);
        mQueue.add(request);
    }



    /**
     * @param context
     * @param msg
     * @param callBack
     * @param rspCls
     */

    public  static void stringGet(final Context context, String url, final String msg,final  NetCallBack<ServerResult> callBack, final Class<?> rspCls) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络异常！");
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);

        LogUtil.d( "net url = " + url);
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Listener<String>() {

                    @Override
                    public void onSuccess(String response) {
                        ServerResult result =null;
                        try {
                            result = (ServerResult) new Gson().fromJson(response, rspCls);
                        }catch (Exception e)
                        {
                            e.getStackTrace();
                        }
                        if (callBack != null)
                            if (response != null) {
                                callBack.success(result);
                            } else {
                                callBack.failed("数据解析出错！");
                            }
                    }

                    @Override
                    public void onPreExecute() {
                        super.onPreExecute();
                        if (msg != null) {
                            progressDialog.setMessage(msg);
                            progressDialog.setCancelable(true);
                            try {
                                if (!progressDialog.isShowing()) {
                                    progressDialog.show();
                                }
                            } catch (Exception e) {

                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        try {
                            progressDialog.cancel();
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    public void onError(NetroidError error) {
                        if (callBack != null)
                            callBack.failed("网络异常！");
                    }
                });
        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        request.setCacheExpireTime(TimeUnit.SECONDS, 3);
//        request.setForceUpdate(true);
        mQueue.add(request);
    }



    /**
     * @param context
     * @param method
     * @param params   form提交用这个方法
     * @param msg
     * @param callBack
     * @param rspCls
     */


    public static void stringPost(final Context context, String method, final Map<String, String> params, final String msg, final NetCallBack<ServerResult> callBack, final Class<?> rspCls) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络异常！");
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        String url = method;
//        LogUtil.d( "net url = " + url);
//        LogUtil.d( "net params = " + params.toString());
        StringPostRequest request = new StringPostRequest(Request.Method.POST, url, params, new Listener<String>() {
            @Override
            public void onSuccess(String response) {
                ServerResult result =null;
                try {
                    result = (ServerResult) new Gson().fromJson(response, rspCls);
                }catch (Exception e)
                {
                    e.getStackTrace();
                }
                if (callBack != null)
                    if (response != null) {
                        callBack.success(result);
                    } else {
                        callBack.failed("数据解析出错！");
                    }
            }

            @Override
            public void onPreExecute() {
                super.onPreExecute();
                if (msg != null) {
                    progressDialog.setMessage(msg);
                    try {
                        if (!progressDialog.isShowing()) {
                            progressDialog.show();
                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    progressDialog.cancel();
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null)
                    callBack.failed("网络异常！");
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }



    //上传文件
    /**
     * @param context
     * @param method
     * @param path   form提交用这个方法
     * @param msg
     * @param callBack
     * @param rspCls
     */


    public static void postPhoto(final Context context, String method, String path, final String msg, final NetCallBack<ServerResult> callBack, final Class<?> rspCls) {
        if (!Utils.isNetworkConnected(context)) {
            if (callBack != null)
                callBack.failed("网络异常！");
            return;
        }

        final CProgressDialog progressDialog = new CProgressDialog(context, R.style.CustomDialog);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        String url = method;


        UploadRequest request = new UploadRequest(Request.Method.POST, url, path, new Listener<String>() {
            @Override
            public void onSuccess(String response) {
                ServerResult result =null;
                try {
                    result = (ServerResult) new Gson().fromJson(response, rspCls);
                }catch (Exception e)
                {
                    e.getStackTrace();
                }
                if (callBack != null)
                    if (response != null) {
                        callBack.success(result);
                    } else {
                        callBack.failed("数据解析出错！");
                    }
            }

            @Override
            public void onPreExecute() {
                super.onPreExecute();
                if (msg != null) {
                    progressDialog.setMessage(msg);
                    try {
                        if (!progressDialog.isShowing()) {
                            progressDialog.show();
                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    progressDialog.cancel();
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(NetroidError error) {
                if (callBack != null)
                    callBack.failed("网络异常！");
            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(request);
    }







    /**
     * 处理token失效方法
     */
    private static void doTokenFail(Context context){
        ToastHelp.doToast(context,"登陆失效，请重新登陆");
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }
}
